import {
  createRouter,
  createWebHistory,
  type RouteRecordRaw,
} from "vue-router";
import NProgress from "nprogress";
import { useUserStore } from "@/store/user";
import menuRoutes from "@/config/routes";
NProgress.configure({
  speed: 500,
  showSpinner: false,
});
// 白名单路径，不需要登录即可访问
const whiteList = ["/login"];
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/dashboard/console",
  },
  ...menuRoutes,
  {
    path: "/login",
    name: "login",
    component: () => import("../views/Login/index.vue"),
    meta: {
      title: "vueAdmin | 登录/注册",
    },
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});
// 路由拦截
router.beforeEach((to, from, next) => {
  const store = useUserStore();
  // 添加路由标题
  if (to.meta?.title) {
    document.title = ("vue admin | " + to.meta.title) as string;
  }
  NProgress.start();
  // TODO: 需要校验登录时间是否过期，如果过期则跳转到登录页
  const loginTime = store.loginTime;
  const isWhiteListPath = whiteList.includes(to.path);
  // 什么情况下需要登录
  if (!loginTime && !isWhiteListPath) {
    next("/login");
  } else {
    next();
  }
});
router.afterEach(() => {
  NProgress.done();
});

export default router;
